import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

/**
 * 简化的数据管理Store，专门用于U9系统数据
 */
export const useDataStore = defineStore('data', () => {
  // 状态
  const fetchedData = ref({})
  const loading = ref(false)
  const errors = ref({})
  
  // 计算属性
  const hasData = computed(() => Object.keys(fetchedData.value).length > 0)
  const errorCount = computed(() => Object.keys(errors.value).length)

  /**
   * 添加获取到的数据
   * @param {string} key - 数据的唯一标识
   * @param {Object} data - 获取到的数据
   * @param {Object} metadata - 元数据信息
   */
  const addData = (key, data, metadata = {}) => {
    fetchedData.value[key] = {
      ...data,
      fetchTime: new Date().toISOString(),
      metadata: metadata
    }
    // 清除该key的错误信息
    delete errors.value[key]
  }

  /**
   * 添加错误信息
   * @param {string} key - 错误的唯一标识
   * @param {string} error - 错误信息
   */
  const addError = (key, error) => {
    errors.value[key] = error
  }

  /**
   * 设置加载状态
   * @param {boolean} isLoading - 是否正在加载
   */
  const setLoading = (isLoading) => {
    loading.value = isLoading
  }

  /**
   * 清空所有数据
   */
  const clearAllData = () => {
    fetchedData.value = {}
    errors.value = {}
  }

  /**
   * 删除指定数据
   * @param {string} key - 要删除的数据key
   */
  const removeData = (key) => {
    delete fetchedData.value[key]
    delete errors.value[key]
  }

  /**
   * 组织数据 - 根据数据类型进行分类
   */
  const organizeData = computed(() => {
    const organized = {
      arrays: {},
      objects: {},
      primitives: {},
      unknown: {}
    }

    Object.entries(fetchedData.value).forEach(([key, dataWrapper]) => {
      // 排除元数据，获取实际数据
      const { fetchTime, metadata, ...actualData } = dataWrapper
      
      // 如果只有一个属性，使用该属性的值
      const data = Object.keys(actualData).length === 1 
        ? Object.values(actualData)[0] 
        : actualData

      const dataName = metadata.name || key

      if (Array.isArray(data)) {
        organized.arrays[dataName] = data
      } else if (typeof data === 'object' && data !== null) {
        organized.objects[dataName] = data
      } else if (['string', 'number', 'boolean'].includes(typeof data)) {
        organized.primitives[dataName] = data
      } else {
        organized.unknown[dataName] = data
      }
    })

    return organized
  })

  /**
   * 按元数据type过滤数据，返回一个伪store对象，兼容DataCategoryTabs
   * @param {string[]} types
   */
  const filterByType = (types = []) => {
    // 只保留指定type的数据
    const filtered = {}
    Object.entries(fetchedData.value).forEach(([key, dataWrapper]) => {
      if (dataWrapper.metadata && types.includes(dataWrapper.metadata.type)) {
        filtered[key] = dataWrapper
      }
    })
    // 构造伪store，兼容DataCategoryTabs
    return {
      fetchedData: filtered,
      totalEndpoints: Object.keys(filtered).length,
      errorCount: 0,
      organizeData: organizeDataFor(filtered),
      hasData: Object.keys(filtered).length > 0
    }
  }

  /**
   * 对指定数据做organizeData分类
   */
  function organizeDataFor(dataObj) {
    const organized = { arrays: {}, objects: {}, primitives: {}, unknown: {} }
    Object.entries(dataObj).forEach(([key, dataWrapper]) => {
      const { fetchTime, metadata, ...actualData } = dataWrapper
      const data = Object.keys(actualData).length === 1 ? Object.values(actualData)[0] : actualData
      const dataName = metadata?.name || key
      if (Array.isArray(data)) organized.arrays[dataName] = data
      else if (typeof data === 'object' && data !== null) organized.objects[dataName] = data
      else if (['string','number','boolean'].includes(typeof data)) organized.primitives[dataName] = data
      else organized.unknown[dataName] = data
    })
    return organized
  }

  return {
    // 状态
    fetchedData,
    loading,
    errors,
    
    // 计算属性
    hasData,
    errorCount,
    organizeData,
    
    // 方法
    addData,
    addError,
    setLoading,
    clearAllData,
    removeData,
    filterByType
  }
})
